//
//  JH_ColorSelView.m
//  ColorSel
//
//  Created by 李江湖 on 2018/1/19.
//  Copyright © 2018年 李江湖. All rights reserved.
//

#import "JH_ColorSelView.h"

@interface JH_ColorSelView()
{
    NSArray *mutarr;
    CGFloat height;
    CGFloat weight;
}
@property (weak, nonatomic) IBOutlet UIScrollView *colorScrollView;

@end
@implementation JH_ColorSelView
-(instancetype)init{
    if ([super init]) {
        height = 20;
        weight = 20;

        [self paddGetinitUI];
    }
    return self;
}
-(void)awakeFromNib{
    [super awakeFromNib];
    height = 20;
    weight = 20;

    [self paddGetinitUI];
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if ([super initWithCoder:aDecoder]) {
        height = 20;
        weight = 20;
        [self paddGetinitUI];
    }
    return self;
}
-(void)setSize:(CGSize)size
{
    _size = size;
    height = _size.height;
    weight = _size.width;
    [self paddGetinitUI];
}
-(instancetype)initWithFrame:(CGRect)frame{
    if ([super initWithFrame:frame]) {
        [self paddGetinitUI];
    }
    return self;
}

-(void)paddGetinitUI{
 
    mutarr = @[@{@"color":[UIColor redColor],@"title":@"红色"},@{@"color":[UIColor yellowColor],@"title":@"黄色"},@{@"color":[UIColor blueColor],@"title":@"蓝色"},@{@"color":[UIColor greenColor],@"title":@"绿色"},@{@"color":[UIColor grayColor],@"title":@"灰色"}];
    if (mutarr.count<=0) {
        return;
    }
    NSInteger totalColumns = mutarr.count;
    CGFloat W = weight ;
    CGFloat wight =  mutarr.count*W+(5*mutarr.count+1);
    CGFloat H = height;
    CGFloat margin = (wight - totalColumns*W)/(totalColumns + 1);
    
    self.colorScrollView.contentSize = CGSizeMake(wight, H);
    [[self.colorScrollView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for (int i = 0; i < mutarr.count; i++)
    {
        UIColor *color = mutarr[i][@"color"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.backgroundColor = color;
        int row = i /totalColumns;
        int col = i %totalColumns;
        CGFloat X = 5 + col *(W + margin);
        CGFloat Y = 0 + row * (H + 20.5);
        button.frame = CGRectMake(X, 0+Y, W, H);
        

        button.tag = 1000 + i;
        [button addTarget:self action:@selector(addBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        //       [button addSubview:image];
        [self.colorScrollView addSubview:button];
    }
}
-(void)addBtnClick:(UIButton *)sender{
    NSInteger  colorIndex = sender.tag - 1000;
    NSDictionary *dic = mutarr[colorIndex];
    if ([self.colordelegate respondsToSelector:@selector(setingColorindex:andTitle:color:)]) {
        [self.colordelegate setingColorindex:colorIndex andTitle:dic[@"title"] color:dic[@"color"]];
    }
}
@end
